<script lang="ts" setup>
import { ref, reactive, watch, watchEffect, onMounted, onUnmounted } from 'vue'

import { objectToQueryParams } from '@/utils/objectToQuery'
import { formatTableCol, getColWidth, setColWidth, setLastWidth } from './FormatData'
import { isDate, formatDate } from '@/utils/formatDate'
import * as BasicApi from '@/api/index'

import Pagination from './Pagination.vue'
import { useMessage } from '@/hooks/useMessage'
const message = useMessage()

import EditModal from './EditModal.vue'
import BreakdownModal from './BreakdownModal.vue'
import eventBus from '@/libs/eventBus'
// import DetailModal from './DetailModal.vue'
// import { checkTagExists } from '@/utils/checkTagExists'

// const props = defineProps(['partParams', 'compName'])
const props = defineProps({
  partParams: {
    type: Object
  },
  compName: {
    type: String
  },
  tableInfo: {
    type: Object
  }
})
const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数

const list = ref<any[]>([]) // 列表的数据
const column = ref<any[]>([]) // 列表的表头

const headList = ref<any[]>([]) // 列表的数据

const selectShow = ref() //列表行多选框
const operList = ref<any[]>([])

const queryParams = reactive({
  type: '',
  value: '',
  keyType: '',
  list: [],
  groupName: '',
  jobType: '',
  pageNo: 1,
  pageSize: 10
})

watch(
  () => props.partParams,
  (val: any) => {
    Object.assign(queryParams, val)
    queryParams.groupName && getList()
  }
)

/** 查询岗位列表 */
const getList = async () => {
  loading.value = true
  try {
    const post = {
      ...queryParams
    }
    const inputStr = objectToQueryParams(post)
    //将Value值放到jsonData中 到时根据keyType是否为多选框再处理Value值
    // keyType为select 直接给数组赋值，若为multiSelect 则取list值
    const selectedList =
      (queryParams.list.length &&
        queryParams.list.map((item) => {
          return {
            value: item
          }
        })) ||
      []
    const jsonData = queryParams.list.length ? selectedList : [{ value: queryParams.value }]
    const result = (await BasicApi.Query({ inputStr, jsonData })) as any
    const { code, msg, data, rsCount } = result
    if (code !== 200) {
      message.error(msg)
      return
    }
    // message.success(msg)
    total.value = rsCount
    if (rsCount == 0) {
      list.value = []
      column.value = []
      operList.value = []
      return
    }
    //格式化数据
    const { listInfo, col } = formatTableCol(data)
    list.value = listInfo || []
    column.value = col || []

    //格式化操作按钮
    const selectArr = data.operInfo && data.operInfo.filter((item: any) => item.Value == 'Select')
    selectShow.value = selectArr && selectArr.length && selectArr[0].IsShow == 'true' ? true : false
  } finally {
    loading.value = false
  }
}

const emit = defineEmits(['selection-change'])
/** 多选操作 */
const handleSelectionChange = (val: any) => {
  val.length && emit('selection-change', val, headList.value)
}

const modalRef = ref()
/** 编辑弹框 */
const handleEdit = (data: any) => {
  modalRef.value.open(queryParams, data)
}

const handleDetail = (data: any, label: string, value: string) => {
  console.log(label, 'label');
  //打开父组件的详情Tab
  eventBus.emit('addDetailTab', {data, label, value})
  setTimeout(() => {
    //并通知详情页渲染
    eventBus.emit('getDetailField', props.tableInfo)
    eventBus.emit('getDetailList', data)
  }, 0)
}
/** 明细弹框 */
const breakdownRef = ref()
const handleBreakdown = (data: any) => {
  breakdownRef.value.open(queryParams, data)
}

/** 删除按钮操作 */
const handleDelete = async (data: any) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    const inputStr = objectToQueryParams({
      groupName: queryParams.groupName,
      jobType: queryParams.jobType,
      operType: 'Delete'
    })
    const jsonData = data
    const result = (await BasicApi.Operate({ inputStr, jsonData })) as any
    const { code, msg } = result
    if (code !== 200) {
      message.error(msg)
      return
    }
    message.success(msg)
    // 刷新列表
    await getList()
  } catch {}
}

// 创建 ref 来引用容器元素
const boxRef = ref()
// 标记容器宽度是否发生变化
const isWidthChanged = ref(false)

const getBoxWidth = () => {
  return boxRef.value?.offsetWidth
}

// 创建 ResizeObserver 实例
let resizeObserver: any
onMounted(() => {
  // 创建 ResizeObserver 实例，传入回调函数
  resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      // 这里可以编写具体要执行的操作，例如更新状态、发送请求等
      // 这里简单地将 isWidthChanged 设置为 true 表示宽度已变化
      isWidthChanged.value = true
      console.log('容器宽度变化为:', entry.contentRect.width)
      if (entry.contentRect.width) {
        // 可以在这里添加更多操作，比如调用某个函数
        performSpecificOperation(entry.contentRect.width)
      }
    }
  })

  // 开始监听容器元素的尺寸变化
  if (boxRef.value) {
    resizeObserver.observe(boxRef.value)
  }
})

onUnmounted(() => {
  // 当组件卸载时，停止监听并清理资源
  if (resizeObserver && boxRef.value) {
    resizeObserver.unobserve(boxRef.value)
  }
})

// 定义一个具体的操作函数
const performSpecificOperation = (newWidth: any) => {
  console.log('执行了特定操作，新宽度为:', newWidth)
  render(newWidth)
  // 这里可以添加更多复杂的操作，如更新数据、调用 API 等
}

const render = (contentWidth?: number) => {
  const result = props.tableInfo
  let resultWidth = contentWidth ? contentWidth : getBoxWidth()
  //渲染表头
  if (result?.fieldInfo?.length) {
    column.value = JSON.parse(JSON.stringify(result.fieldInfo))
    // //含有selection则宽度 - 50
    if (selectShow.value) {
      resultWidth = resultWidth - 50
    }
    //当宽度之和等于百分比的时候 最后一列需要处理 解决小空隙问题
    const sumPercent = column.value.reduce((first, cur) => first + cur.width, 0)
    if (sumPercent > 100) {
      column.value = getColWidth(column.value, resultWidth)
    } else {
      column.value = getColWidth(column.value, resultWidth)
      setLastWidth(column.value, resultWidth)
    }
  }
  //行操作
  const len = result?.pageInfo?.lineOperate.length
  if (list.value.length && len && result?.fieldInfo?.length) {
    resultWidth = len && resultWidth - 120
    const temp = JSON.parse(JSON.stringify(result.fieldInfo))
    //当宽度之和等于百分比的时候 最后一列需要处理 解决小空隙问题
    const sumPercent = temp.reduce((first: any, cur: any) => first + cur.width, 0)
    if (sumPercent > 100) {
      column.value = getColWidth(temp, resultWidth)
    } else {
      column.value = getColWidth(temp, resultWidth)
      setLastWidth(column.value, resultWidth)
    }
    operList.value = result?.pageInfo?.lineOperate || []
  }
}

watchEffect(() => {
  render()
})

const refreshList = (width: number) => {
  render(width)
}
eventBus.on('refreshList', refreshList)
</script>
<template>
  <div ref="boxRef">
    <el-table
      v-loading="loading"
      :data="list"
      stripe
      border
      style="width: 100%"
      highlight-current-row
      :header-cell-style="{ background: '#eaf6fb' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="selectShow" align="center" type="selection" width="50" />
      <template v-for="item in column" :key="item.value">
        <el-table-column
          v-if="item.isShow == 'true'"
          align="center"
          :label="item.label"
          :width="item.width"
          show-overflow-tooltip
        >
          <template #default="scope">
            <template v-if="isDate(item.value)">
              <span>{{ formatDate(scope.row[item.value]) }}</span>
            </template>
            <template v-else>
              <span>{{ scope.row[item.value] }}</span>
            </template>
          </template>
        </el-table-column>
      </template>

      <el-table-column v-if="operList.length" fixed="right" label="操作" align="center" width="120">
        <template #default="scope">
          <template v-for="(item, index) in operList" :key="index">
            <el-button
              v-if="item.value == 'Edit'"
              link
              type="primary"
              @click="handleEdit(list[scope.$index])"
            >
              {{ item.label }}
            </el-button>
            <el-button
              v-if="item.value == 'WorkFlow'"
              link
              type="warning"
              @click="handleDetail(list[scope.$index], item.label, item.value)"
            >
              {{ item.label }}
            </el-button>
            <el-button
              v-if="item.value == 'Delete'"
              link
              type="danger"
              @click="handleDelete(list[scope.$index])"
            >
              {{ item.label }}
            </el-button>
            <el-button
              v-if="item.value == 'Breakdown'"
              link
              type="success"
              @click="handleBreakdown(list[scope.$index])"
            >
              {{ item.Label }}
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <Pagination
    class="mt-4"
    :total="total"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />
  <!-- 编辑弹框 -->
  <EditModal ref="modalRef" @refresh="getList" />
  <!-- 明细弹框 -->
  <BreakdownModal ref="breakdownRef" />
  <!-- 表单弹窗：只读详情 -->
  <!-- <DetailModal ref="detailRef" /> -->
</template>
<style lang="less" scoped>
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
  background: #eee;
}
/* 自定义表头列之间的边框颜色 */
:deep(.el-table__header th, .el-table__body td) {
  border-right-color: #dfdfdf;
}
:deep(.el-table__cell) {
  border-right-color: #dfdfdf;
}
:deep(.el-table__row--striped .el-table__cell) {
  border-right-color: #dfdfdf;
}
</style>
